<template>
	<view class="mine" v-if="user">
		<view class="user-header">
			<image src="/static/images/drink-header.png" mode="" class="background-img"></image>
			<view class="section">
				<view class="section-top">
					<view class="section-one">
						
						<view class="user-img-box" @click="goToMyProfile()">
							<image :src="user.avatar_url" mode="" class="user-img"></image>
						</view>
					</view>
					<view class="section-two" v-if="user.vip_expired_at">
						<!-- <view v-if="user.vip.ex"></view> -->
						<view class="user-name">{{ user.name }}</view>
						<view class="user-vip-expired">{{ user.vip_expired_at }}</view>
						
					</view>
					<view class="section-two-no" v-else>
						<view class="user-name">{{ user.name }}</view>
					</view>
					
				</view>
				
				<view class="section-bottom">
					<view>开通无限畅饮</view>
					
					<view class="vip-card" v-for="(category, index) in categories" :key="index" :class="{'item-active': activeIndex === index}" @click="onClick(index)">
						<view class="vip-title">{{category.name}}</view>
						<view class="vip-market" :class="{'item-active_market': activeIndex === index}">¥ {{category.price_lowest}}</view>
						<view class="vip-lowest" :class="{'item-active_money': activeIndex === index}">¥ {{category.price_market}}</view>
					</view>
					
					
				</view>
			</view>
			
			
		</view>
	
		<view class="welfare">
			<view class="welfare-top">
				<image src="/static/images/welfare-icon.png" mode="" class="welfare-top-icon"></image>
				<view>恭喜您，获得限量畅饮大礼包</view>
			</view>
			
			<scroll-view scroll-x scroll-width-animation class="content" :scroll-left="scrollLeft">
			  <view class="items">
			    <block v-for="(category, index) in categories" :key="index">
					<view :id="'_c_' + index" class="item"  :class="{'item-other-active': activeIndex === index}" :style="{color: activeIndex === index ? defaultConfig.activeColor : defaultConfig.textColor}" @click="onClick(index)">{{ category.name }}</view>
				</block>
			  </view>
			  <view
			      class="underline"
			      :style="{
			        transform: 'translateX('+underline.left+'px)',
			        width: defaultConfig.underlineWidth,
			        backgroundColor: defaultConfig.underlineColor
			  }"></view>
			</scroll-view>
			
			<view class="welfare-detail">
				<view class="welfare-item" v-for="(welfare, index) in welfares" :key="index">
					<view>{{welfare.name}}</view>
					<block v-for="(detail, dIndex) in welfare.details" :key="dIndex">
						 <view v-if="detail.type==='phone'">
							 <view class="welfare-item-desc" >
							 	<view class="item-left">
							 		<image src="/static/images/hfcz.png" mode=""  class='phone'></image>
							 	</view>
							 	
							 	<view class="item-center-product">
							 		<view class="title" >{{detail.phone_bill_name}}</view>
							 		<input type="number" pattern="\d*" maxlength="11"  placeholder="请输入手机号" placeholder-style="color:#999999;font-size:28rpx;" v-on:input="change(detail.welfare_id,welfare.id)"  v-bind:value="phoneNumber" class="reg-ipt"/>
							 		
							 	</view>
							 	<view class="item-bottom">
							 			<view class="btn">输入手机号码</view>
							 	</view>
							 </view>
						 </view>
						 <view v-else-if="detail.type==='coupon'">
							 <view class="welfare-item-desc" >
								<view class="item-left">
									<image src="/static/images/coupon-image.png" mode=""  class="coupon"></image>
								</view>
								
								<view class="item-center-product">
									<view class="title">{{categories[activeIndex].price_lowest}}元组合代金劵</view>
									<view class="coupon-list">
										<view v-for="(coupon, cIndex) in detail.coupons" :key="cIndex">{{coupon.name}}*{{coupon.number}}</view>
									</view>
									
								</view>
								<view class="item-bottom">
									<view class="radio">
										<image src="/static/images/desc-icon-selected.png" mode="" v-if='isAgree' @click="handleClick(detail.welfare_id,welfare.id)" class='buy-xz-image'></image>
										<image src="/static/images/desc-icon.png" mode="" v-else  @click="handleClick(detail.welfare_id,welfare.id)" class='buy-xz-image'></image>
									</view>
								</view>
							 </view>
						 </view>
						 <view v-else-if="detail.type==='drink'">
							 <view class="welfare-item-desc" >
								<view class="item-left">
									<image :src="detail.product.cover_url" mode=""   class="product"></image>
								</view>
								
								<view class="item-center-product">
									<view class="title">{{detail.product.title}}</view>
									<view class="address" >
										<view v-if="currentAddress">{{ currentAddress.address }}</view>
										<view v-else>未填写收货地址</view>
									</view>
									
								</view>
								<view class="item-bottom">
									<view class="money">¥{{detail.product.price_market}}</view>
									<view class="btn" @click="chooseAddress">填写地址</view>
								</view>
							 </view>
						</view>
						<view v-else>
							<block v-for="(product, pIndex) in detail.products" :key="pIndex">
								 <view class="welfare-item-desc" >
									<view class="item-left">
										<image :src="product.cover_url" mode=""   class="product"></image>
									</view>
									
									<view class="item-center-product">
										<view class="title">{{product.title}}</view>
										<view class="address" >
											<view v-if="currentAddress">{{ currentAddress.address }}</view>
											<view v-else>未填写收货地址</view>
										</view>
										
									</view>
									<view class="item-bottom">
										<view class="money">¥{{product.price_market}}</view>
										<view class="radio-product">
											<image src="/static/images/desc-icon-selected.png" mode="" v-if='productAgree[pIndex]===true' @click="handleClickProduct(pIndex,detail.welfare_id,product.id,welfare.id)" class='buy-xz-image'></image>
											<image src="/static/images/desc-icon.png" mode="" v-else  @click="handleClickProduct(pIndex,detail.welfare_id,product.id,welfare.id)" class='buy-xz-image'></image>
										</view> 
										
									</view>
								 </view>
							</block>
						</view>
					</block>	 
					
				</view>
				
			</view>
			<view class="buy-vip" v-if="categories[activeIndex]" @click="submitVip">
				<view>{{categories[activeIndex].name}}<text> ¥ {{categories[activeIndex].price_lowest}}</text></view>
				<view>去支付</view>
			</view>
		</view>
	</view>
</template>

<script>
	import store from "store"
	import { mapMutations,mapGetters,mapActions } from 'vuex'
	import Skeleton from "mixins/Skeleton"
	import AuthChecking from "mixins/AuthChecking"
	import SkeletonMineCom from "skeletons/SkeletonMineCom"
	import { vipWelfare,vipCategory,createVip } from "api/vipPurchaseApi"
	import { getUser } from "api/userApi"
	import { balancepay,wxpaym,spendpay,goldCoinPay } from "helpers/paymentHelper"
	export default {
		store,
		mixins: [
			Skeleton,
			AuthChecking
		],
		watch: {
		  config: {
		    handler(val) {
		      this.defaultConfig = { ...this.defaultConfig, ...val }
		    },
		    immediate: true
		  }
		},
		computed:{
			...mapGetters([
				'user',
				'isLogin',
				'currentAddress',
			])
		},
		components: {
			SkeletonMineCom
		},
		data() {
			return {
				estimateData:null,
				counts:null,
				downPopShow:false,
				shopingMoneyShow:false,
				categories:[],
				activeIndex:1,
				scrollLeft: 0,
				welfares:[],
				phoneNumber: '',
				isAgree:false,
				productAgree:[],
				choiceItem:[],
				drinkItem:{},
				form: {},
				defaultConfig: {
				  textColor: '#999',
				  activeColor: '#000000',
				  underlineWidth: 50,
				  underlineColor: '#E57034'
				},
				underline: {
				  left: 0
				}
			}
		},
		methods: {
			...mapActions([
				'getDefaultAddress',
				'updateIsAddressChosenForOrder'
			]),
			...mapMutations(['setUser']),
			change(welfare_detail_id,id){
				this.phoneNumber=event.target.value;
				this.choiceItem[id] = {
					'phoneNumber' : this.phoneNumber,
					'welfare_detail_id' : welfare_detail_id,
				}
				if(this.productAgree){
					this.productAgree.forEach((item, index) => {
						this.productAgree[index]=false;
					})
					this.$forceUpdate();
				}
				
			},
			updateUnderline() {
			  let list = this.categories
					if (list.length === 0) return;
			  const query = uni.createSelectorQuery().in(this)
			  this.categories.forEach((item, index) => {
			    query.select('#_c_' + index)
			        .boundingClientRect((res) => {
			          if (res) {
								
			            item._underline = {
			              left: res.left + (res.width - this.defaultConfig.underlineWidth) / 2
			            }
			            if (list.length - 1 === index) {
			              this.slideToIndex()
			            }
			          }
			        }).exec()
			  })
					
					/* this.categories = list;
					console.log(this.categories);return false; */
			},
			slideToIndex() {
			  const index = this.activeIndex
			  this.underline = {
			    left: this.categories[index]._underline.left
			  }
			  this.scrollLeft = this.activeIndex * this.defaultConfig.underlineWidth * 2
			},
			handleClick(welfare_detail_id,id) {
				this.isAgree = !this.isAgree
				if(this.isAgree){
					this.choiceItem[id] = {
						'welfare_detail_id' : welfare_detail_id,
					}
					
				}else{
					delete this.choiceItem[id];
				}
				
			},
			handleClickProduct(index,welfare_detail_id,product_id,id) {
				this.phoneNumber='';
				this.productAgree[index] = !this.productAgree[index];
				
				if(this.productAgree[index]){
					this.productAgree.forEach((agree, aindex) => {
						this.productAgree[aindex] = false;
					})	
					this.productAgree[index] = true;
				}
				if(this.productAgree[index]){
					this.choiceItem[id] = {
						'product_id' : product_id,
						'welfare_detail_id' : welfare_detail_id,
					}
					
				}else{
					delete this.choiceItem[id];
				}
				
				this.$forceUpdate() 
			},
			async payCurrentVip(id) {
				
				await balancepay(id, 'vipPurchase')
				uni.setStorage({
					key: 'payid',
					data: id
				});
				return false;
				if (this.orderPayment === 'balance') {
					await balancepay(id, 'order')
					uni.setStorage({
						key: 'payid',
						data: id
					});
				}
				
				if (this.orderPayment === 'shoppingmoney') {
					await spendpay(id, 'order')
					uni.setStorage({
						key: 'payid',
						data: id
					});
				}
				
				if(this.orderPayment === 'goldcoinsmoney'){
					await goldCoinPay(id, 'order')
					uni.setStorage({
						key: 'payid',
						data: id
					});
				}
				
				if (this.orderPayment === 'weixin') {
					const payload = await payOrderByAdapayWxmini(id)
					let jumpPayUrl = ''
					if(this.isWeiXinLogin){
						jumpPayUrl = payload.result.wx_h5_pay_url;
					}else{
						jumpPayUrl = payload.result.scheme_code;
					}
					window.location.href = jumpPayUrl;
				}
				
				if (this.orderPayment === 'alipay') {
					const payload = await payOrderByAliwap(id)
					document.querySelector('body').innerHTML = payload.result;
					await document.forms[0].submit()
					uni.reLaunch({
						url:'/pages/index/index'
					})
					// uni.setStorage({
					// 	key: 'payid',
					// 	data: this.order.id
					// });
					// uni.navigateTo({
					// 	url:'/packs/pages/order/paid'
					// })
				}
				
				
			},
			async submitVip() {
				
				if (!this.currentAddress) {
					uni.showToast({
						title: '请选择收货地址'
					})
					return
				}else{
					
					if(this.drinkItem.welfare_id){
						this.choiceItem[this.drinkItem.welfare_id] = {
							'product_id' : this.drinkItem.product_id,
							'welfare_detail_id' : this.drinkItem.welfare_detail_id,
						}
					}
				}
				let formItem = [];
				let i = 0;
				this.choiceItem.forEach((item, index) => {
					formItem[i] =item;
					i++;
				
				})	
				
				if(formItem.length < this.welfares.length){
					
					uni.showToast({
						title: '请选全福利'
					})
					return
					
				}
				
				this.form.items = formItem;
				this.form.address_id = this.currentAddress.id
				this.form.vip_category_id = this.categories[this.activeIndex].id
				
				
				let response = await createVip(this.form);
				if(response.id){
					await this.payCurrentVip(response.id);
				}
				
			},
			async onClick(index) {
			  this.activeIndex = index
			  this.slideToIndex();
			
			},
			async getUser(){
				let response =  await getUser()
				this.setUser(response)
			},
			async getVipCategory() {
				const response = await vipCategory()
				
				this.categories = response
				if(this.categories){
					let welfareId = this.categories[this.activeIndex].id;
					this.getVipWelfare(welfareId);
				}
				
				
			},
			async getVipWelfare(id) {
				const response = await vipWelfare(id)
				this.welfares = response;
				this.welfares.forEach((welfare, index) => {
					welfare.details.forEach((detail, dindex) => {
						if(detail.type=='product'){
							detail.products.forEach((product, pindex) => {
								this.productAgree[pindex] = false;
							})		
							
						}
						if(detail.type=='drink'){
							this.drinkItem = {
								'welfare_id' : welfare.id,
								'welfare_detail_id' : detail.welfare_id,
								'product_id' : detail.product.id
							}
						}
					})	

				})
				
			},
			async chooseAddress() {
				await this.updateIsAddressChosenForOrder(true);
				uni.navigateTo({
					url: `/packs/pages/address/index`
				})
			}
		},
		async onShow() {
			if(await this.isLogin){
				await this.getUser()
				await this.getVipCategory();
				this.getDefaultAddress();
				setTimeout(() => {
				  this.updateUnderline()
				}, 10)
			}
			uni.setStorage({
				 key:"newsTop",
				 data:0
			})
		},
		onLoad() {
			/* if (window.history && window.history.pushState) {
				history.pushState(null, null, document.URL);
			} */
		}
	}
</script>

<style lang="scss" scoped >
	page{
		background: #F6F6F6;
		width: 100%;
		height: 100%;
		overflow-y: auto;
		position: fixed;
		left:0;
		top:0;
	}
	.user-header{
		width: 750rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		margin:0 auto ;
		position:relative;
		.background-img{
			width:100%;
			height:670rpx;
			
		}
	}
	.section{
		position:absolute;
		top:188rpx;
		width:100%;
	}
	.section-one{
		align-items: center;
		justify-content: space-between;
		float:left;
		
	}
	.user-img-box{
		width: 116rpx;
		height: 116rpx;
		position: relative;
		margin-left: 16rpx;
	}
	.user-img{
		display: block;
		width: 116rpx;
		height: 116rpx;
		border-radius: 50%;
	} 
	 
	.section-top{
		overflow:hidden;
		color:#fff;
	}
	.section-two-no{
		float:left;
		align-items: center;
		margin-top: 16rpx;
		margin-left: 18rpx;
		color:#fff;
		.user-name{
			font-size: 32rpx;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #fff;
			margin-top:22rpx;
			
		}
	}
	.section-two{
		float:left;
		align-items: center;
		margin-top: 16rpx;
		margin-left: 18rpx;
		color:#fff;
		.user-name{
			font-size: 32rpx;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #fff;
			
		}
		.user-vip-expired{
			font-size: 26rpx;	
		}
	}
	.section-three{
		float:right;
		color:#fff;
		margin-right:30rpx;
		margin-top:38rpx;
		overflow:hidden;
		>image{
			width:32rpx;
			height:20rpx;
			float:left;
			margin-right:6rpx;
			margin-top:6rpx;
		}
		>view{
			float:left;
			font-size:24rpx;
		}
	}
	.section-bottom{
		width:718rpx;
		height:596rpx;
		border-radius:20rpx;
		margin:18rpx auto 0rpx;
		//background:linear-gradient(#F5D8BE,#FDF9F0,#CFA785);
		background:#fff;
		
		>view:nth-child(1){
			margin-left:30rpx;
			padding-top:22rpx;
			font-size:26rpx;
			font-weight:600;
			
		}
		.vip-card{
			width:694rpx;
			height:196rpx;
			border-radius:10rpx;
			background:linear-gradient(#FBE7D0,#FCEEDD,#FAE3C0);
			margin:50rpx auto 0rpx;
			overflow:hidden;
			position:relative;
			line-height:196rpx;
			.vip-title{
				font-size:40rpx;
				color:#51422D;
				font-weight:600;
				margin-left:18rpx;
				float:left;
			}
			.vip-lowest{
				font-size:40rpx;
				color:#E66D30;
				font-weight:600;
				margin-right:32rpx;
				float:right;
			}
			.vip-market{
				font-size:32rpx;
				color:#A89C89 ;
				font-weight:600;
				margin-right:42rpx;
				float:right;
				text-decoration:line-through;
			}
		}
	}
	
	.item-active{
		background:linear-gradient(#F6E7D3,#D8A87E) !important;
		
	}
	.item-active_money{
		color:#51422D !important;
		
	}
	.item-active_market{
		color:#fff !important;
		
	}
    .welfare{
		margin-top:266rpx;
		background:#fff;
		.welfare-top{
			
			height:180rpx;
			display:flex;
			padding-top:24rpx;
			line-height:180rpx;
			>image{
				margin-left:28rpx;
				height:180rpx;
				width:180rpx;
			}
			>view{
				margin-left:28rpx;
				font-size:28rpx;
				color:#000;
			}
		}
	}
	.content {
	  white-space: nowrap;
	  width: 100%;
	  height: 90rpx;
	  box-sizing: border-box;
	  position: relative;
	  margin-top:22rpx;
	  .items {
	    height: 72rpx;
		line-height:72rpx;
	    .item {
	      display: inline-block;
	      position: relative;
	      padding: 0 30rpx;
	      height: 100%;
		  color:#999;
		  font-size:28rpx;
	      text-align: center;
	      &-active {
	        color: red;
	        font-weight: bold;
	      }
					.top-num{
						// font-size: 28rpx;
						// color:#FF4924;
					}
					// .top-num{
					// 	font-size: 20rpx;
					// 	color:red;
					// 	width: 50rpx;
					// 	height: 30rpx;
					// 	position: absolute;
					// 	display: flex;
					// 	align-items: center;
					// 	justify-content: center;
					// 	border-radius:6rpx;
					// 	right:-20rpx;
					// 	top:10rpx;
					// 	background: linear-gradient(90deg, #FDE1F3 0%, #FFF5ED 100%);
					// }
	    }
	  }
	  .underline {
	    position: absolute;
	    bottom: -1;
	    width: 100rpx;
	    height: 6rpx;
	    display: block;
	    transition: .5s;
	  }
	}
	.item-other-active{
		font-size:36rpx !important;
		color:#E57034 !important;
		font-weight:600 !important;
	}
	.welfare-detail{
		.welfare-item{
			margin-top:22rpx;
			>view:nth-child(1){
				font-size:28rpx;
				color:#333;
				margin-left:28rpx;
			}
			.welfare-item-desc{
				
				width:732rpx;
				height:246rpx;
				margin:22rpx auto 0rpx;
				background:url('/static/images/vip-border.png') no-repeat;
				background-size:732rpx 246rpx; 
				display:flex;
				.item-left{
					width:258rpx;
					text-align:center;
					.phone{
						width:158rpx;
						height:96rpx;
						margin-top:68rpx;
					}
					.coupon{
						width:192rpx;
						height:92rpx;
						margin-top:68rpx;
					}
					.product{
						width:198rpx;
						height:196rpx;
						margin-top:24rpx;
					}
				}
				.item-center-product{
					width:248rpx;
					position:relative;
					margin-left:6rpx;
					.title{
						height:68rpx;
						font-size:24rpx;
						color:#000;
						margin-top:52rpx;
						
					}
					.address{
						font-size:24rpx;
						color:#999;
						position:absolute;
						bottom:56rpx;
						
						>view{
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
							width:254rpx;
						}
					}
					.reg-ipt{
						font-size:24rpx;
						color:#999;
						position:absolute;
						bottom:56rpx;
						
					}
					.coupon-list{
						font-size:24rpx;
						color:#999;
					}
					
				}
				.item-bottom{
					position:relative;
					width:180rpx;
					.money{
						font-size:32rpx;
						color:#010101;
						 margin-top:48rpx;
						 margin-left:62rpx;
						
					}
					.btn{
						font-size:24rpx;
						color:#51422D;
						background:#F8D39C;
						width:156rpx;
						height:38rpx;
						line-height:38rpx;
						text-align:center;
						position:absolute;
						right:0rpx;
						bottom:56rpx;
						
					}
					.radio{
						position:absolute;
						right:0rpx;
						bottom:82rpx;
						
					}
					.radio-product{
						
						position:absolute;
						right:0rpx;
						bottom:56rpx;
					}
					
				}
			}
		}
		
	}
	.buy-vip{
		width:616rpx;
		height:112rpx;
		line-height:112rpx;
		background:url('/static/images/buy-vip-btn.png') no-repeat;
		background-size:616rpx 112rpx; 
		margin:34rpx auto 0rpx;
		display:flex;
		position:relative;
		>view:nth-child(1){
			font-size:32rpx;
			color:#EFE1C6;
			margin-left:28rpx;
			>text{
				color:#FF814F;
				margin-left:5rpx;
			}
		}
		>view:nth-child(2){
			font-size:40rpx;
			color:#fff;
			font-weight:600;
			position:absolute;
			right:76rpx;
		}
	}
	.buy-xz-image{
		width:32rpx;
		height:32rpx;
	}
</style>
